<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>添加攻略</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <style>
    .strategy {
      width: 500Px;
    }
  </style>
</head>

<body>
  <div id="strategy">

    <div style="position: fixed;right: 20%;top: 15%;width: 200px;">
      介绍数据： {{ruleForm}}
    </div>
    <div class="strategy">
      <el-form :model="ruleForm" ref="ruleForm" label-width="130px" class="demo-ruleForm" status-icon
        @submit.native.prevent>
        <!-- 游点介绍 -->
        <div v-for="(pGroupItem, pGroupIndex) in ruleForm.pointsGroup"
          style="border: 1px solid #abcdef;padding: 20px;position: relative;">
          <el-form :model="pGroupItem" ref="pGroupItemTitle" label-width="100px" class="demo-ruleForm" status-icon
            @submit.native.prevent>
            <el-form-item label="添加游点标题" prop="title" :rules="rules.title">
              <el-input clearable v-model="pGroupItem.title" maxlength="100" placeholder="请添加游玩标题" show-word-limit>
              </el-input>
            </el-form-item>
          </el-form>

          <div style="border: 1px solid saddlebrown;">
            <div style="min-height: 300px;">
              <draggable v-model="pGroupItem.points" :options="{group:'people'}">
                <div v-for="(pointsItem, pointsIndex) in pGroupItem.points" style="padding: 5px">
                  <div v-if="pointsItem.type == 'text'" style="line-height: 2">
                    <div style="border: 1px dotted #cccccc;border-radius: 4px;position: relative;">
                      <div @click="pointTextClick(pointsItem.val, pGroupIndex, pointsIndex)">{{pointsItem.val}}</div>
                      <el-popover placement="top" width="160" v-model="pointsItem.IsDel">
                        <p>确定删除内容吗？</p>
                        <div style="text-align: right; margin: 0">
                          <el-button size="mini" type="text" @click="pointsCancel(pGroupIndex, pointsIndex)">
                            取消
                          </el-button>
                          <el-button type="primary" size="mini" @click="delpoints(pGroupIndex, pointsIndex)">
                            确定</el-button>
                        </div>
                        <span class="el-icon-error" slot="reference"
                          style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"></span>
                      </el-popover>
                    </div>
                  </div>
                  <!-- img -->
                  <div v-else>
                    <div style="border: 1px dotted #cccccc;border-radius: 4px;position: relative;">
                      <!-- <el-image :src="pointsItem.imgList.url"></el-image> -->
                      <el-image :src="pointsItem.imgList.url"></el-image>
                      <el-popover placement="top" width="160" v-model="pointsItem.IsDel">
                        <p>确定删除内容吗？</p>
                        <div style="text-align: right; margin: 0">
                          <el-button size="mini" type="text" @click="pointsCancel(pGroupIndex, pointsIndex)">
                            取消
                          </el-button>
                          <el-button type="primary" size="mini" @click="delpoints(pGroupIndex, pointsIndex)">
                            确定</el-button>
                        </div>
                        <span class="el-icon-error" slot="reference"
                          style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"></span>
                      </el-popover>
                    </div>
                  </div>
                </div>
              </draggable>
            </div>
            <div class="btnGroup" style="display: flex;justify-content: flex-end;">
              <el-button size='mini' type="primary" @click='addTextFc(pGroupIndex)'>添加文本</el-button>
              <el-button size='mini' type="primary" @click='addImgFc(pGroupIndex)'>添加图片</el-button>
            </div>
          </div>
          <el-form :model="pGroupItem" ref="pGroupItem" label-width="100px" class="demo-ruleForm" status-icon
            @submit.native.prevent>
            <el-form-item label="请选择关联资源" prop="Product" :rules="rules.optionProduct">
              <el-select v-model="pGroupItem.Product" multiple placeholder="请选择">
                <el-option v-for="item in optionProduct" :key="item.id" :label="item.title" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-popover placement="top" width="160" v-model="pGroupItem.IsDel">
            <p>确定删除内容吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="pointsGroupCancel(pGroupIndex)">
                取消
              </el-button>
              <el-button type="primary" size="mini" @click="delpointsGroup(pGroupIndex)">
                确定</el-button>
            </div>
            <span class="el-icon-error" slot="reference"
              style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"></span>
          </el-popover>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addPlayPiece">添加游玩点</el-button>
          <el-button type="primary" @click="submitForm">立即创建</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :visible.sync="globalMagnify">
      <img width="100%" :src="globalMagnifyUrl">
    </el-dialog>
    <!-- 富文本的text添加 -->
    <el-dialog :title="TextTitle" :visible.sync="addText" @close="globalTextClose">
      <el-input type="textarea" v-model="globalText" show-word-limit maxlength="500"
        :autosize="{ minRows: 1, maxRows: 10}" clearable></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="gloablTextCancel">取 消</el-button>
        <el-button type="primary" @click="gloablTextConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 富文本的img添加 -->
    <el-dialog title="添加图片" :visible.sync="addImg" @close="globalImgClose">
      <div style="width: 600px;height: 550px;">
        <vue-cropper ref="cropper" :img="cropperOption.img" :output-size="cropperOption.size"
          :output-type="cropperOption.outputType" :info="true" :full="cropperOption.full"
          :can-move="cropperOption.canMove" :can-move-box="cropperOption.canMoveBox" :fixed-box="cropperOption.fixedBox"
          :original="cropperOption.original" :auto-crop="cropperOption.autoCrop"
          :auto-crop-width="cropperOption.autoCropWidth" :auto-crop-height="cropperOption.autoCropHeight"
          :center-box="cropperOption.centerBox" @real-time="realTime" :high="cropperOption.high" @img-load="imgLoad"
          mode="cover"></vue-cropper>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="gloablImgCancel">取 消</el-button>
        <el-button type="primary" @click="gloablImgConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 全局input选择文件 -->
    <input type="file" ref="myInput" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
      accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
  </div>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- 生产环境版本，优化了尺寸和速度 -->
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <!-- 拖拽包 -->
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.7.0/Sortable.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script>
  <script src='./cos-js-sdk-v5.min.js'></script>
  <!-- vue图片裁剪 -->
  <script src="https://cdn.jsdelivr.net/npm/vue-cropper@0.4.9/dist/index.min.js"></script>
  <script>
    Vue.use(window['vue-cropper'])
    var Bucket = ''
    var Region = ''
    let config = {
      url: 'http://wl.fangkeng.wang/admin/'
    }
    var cos = new COS({
      getAuthorization: function (options, callback) {
        // var url = 'http://wl.fangkeng.wang/api/test/test';
        var url = config.url + 'cosv5';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onload = function (e) {
          try {
            var data = JSON.parse(e.target.responseText);
            Bucket = data.Bucket;
            Region = data.Region;
          } catch (e) {
          }
          callback({
            TmpSecretId: data.credentials && data.credentials.tmpSecretId,
            TmpSecretKey: data.credentials && data.credentials.tmpSecretKey,
            XCosSecurityToken: data.credentials && data.credentials.sessionToken,
            ExpiredTime: data.expiredTime,
          });
        };
        xhr.send();
      }
    });
    function http(url, method, data) {
      return new Promise((res, rej) => {
        axios({
          url,
          method,
          data
        }).then(pos => res(pos)).catch(err => rej(err))
      })
    }
    function allCheckRules(that, formName, index) {
      let result
      result = new Promise((resolve, reject) => {
        if (index) {
          that.$refs[formName][(index - 1)].validate((valid) => {
            if (valid) {
              resolve();
            } else { reject() }
          })
        } else {
          that.$refs[formName].validate((valid) => {
            if (valid) {
              resolve();
            } else { reject() }
          })
        }
      })
      return result
    }
    var strategy = new Vue({
      el: '#strategy',
      data: {
        // 裁剪配置
        cropperOption: {
          img: '',
          size: 1,
          full: false,
          outputType: 'png',
          canMove: true,
          // fixedBox为true就不能改变裁剪框
          fixedBox: false,
          original: false,
          canMoveBox: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 200,
          autoCropHeight: 150,
          centerBox: false,
          high: true
        },
        moveState: '', // 裁剪的状态
        scenicList: [{ id: 0, title: '羊肉粉' }, { id: 1, title: '红烧肉' }, { id: 2, title: '煎饼' }], // 景点选
        pGroupIndex: null,
        addText: false, // 添加文本
        addImg: false, // 添加img
        globalText: '', // globalText
        globalImg: [], // globalImg
        globalMagnify: false, // 是否显示全局放大镜
        globalMagnifyUrl: '', // 全局放大镜的本地url
        disabled: false,
        pointsNum: 0, // 商品的index
        pointsItemIndex: 0, // points里的index
        isTextUpdataState: false, // 文本修改状态
        isImgUpdataState: false, // img修改状态
        TextTitle: '', // 富文本text的title
        optionProduct: [{ id: 0, title: '香菜' }, { id: 1, title: '肉夹馍' }, { id: 2, title: '酸菜' }],
        ruleForm: {
          // 商品组
          pointsGroup: [
            { points: [], Product: [], IsDel: false, title: '' }
          ],

        },
        rules: {
          // 攻略标题
          title: [
            { required: true, message: '请添加标题', trigger: ['change', 'blur'] }
          ],
          // 商品组tit
          pointsItemTit: [
            { required: true, message: '请添加商品名称', trigger: ['change', 'blur'] }
          ],
          // pointsItemImg 请添加商品图片
          pointsItemImg: [
            { type: 'array', required: true, message: "请添加商品图片(1-5张)", trigger: ['change', 'blur'] }
          ],
          // 选择产品
          optionProduct: [
            { required: true, message: '至少选择一款', trigger: ['change', 'blur'] }
          ],
        }
      },
      created() {
        http(config.url + 'getScenic', 'POST', {}).then(pos => this.scenicList = pos.data.data)
        // 获取资源
        http(config.url + 'getResource', 'POST', {}).then(pos => this.optionProduct = pos.data.data)

      },
      methods: {
        // 选择图片
        uploadImg(e, num) {
          //上传图片
          // this.option.img
          var file = e.target.files[0]
          if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
            alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
            return false
          }
          var reader = new FileReader()
          reader.onload = (e) => {
            let data
            if (typeof e.target.result === 'object') {
              // 把Array Buffer转化为blob 如果是base64不需要
              data = window.URL.createObjectURL(new Blob([e.target.result]))
            } else {
              data = e.target.result
            }
            if (num === 1) {
              this.cropperOption.img = data
            } else if (num === 2) {
              this.example2.img = data
            }
          }
          // 转化为base64
          // reader.readAsDataURL(file)
          // 转化为blob
          reader.readAsArrayBuffer(file)
          this.addImg = true
          this.ImgUtilsTitle = '添加图片'
        },
        imgLoad(msg) {
          console.log(msg)
        },
        realTime(data) {
          this.moveState = data
        },
        // 点击富文本文字修改
        pointTextClick(val, pGroupIndex, pointsIndex) {
          this.TextTitle = '修改文本'
          this.pointsNum = pGroupIndex
          this.pointsItemIndex = pointsIndex
          this.addText = true
          this.globalText = val
          this.isTextUpdataState = true
        },
        globalImgClose() {
          this.globalImg = []
        },
        globalTextClose() {
          this.globalText = ''
        },
        // 删除游玩点
        delpointsGroup(pGroupIndex) {
          this.ruleForm.pointsGroup.splice(pGroupIndex, 1)
        },
        // 游玩点 组取消
        pointsGroupCancel(pGroupIndex) {
          this.ruleForm.pointsGroup[pGroupIndex].IsDel = false
        },
        // 添加游玩点
        addPlayPiece() {
          let obj = { points: [], Product: [] }
          let that = this
          let arr = []
          // this.ruleForm.pointsGroup.push(obj)
          let list = this.ruleForm.pointsGroup
          list.map((item, index) => {
            arr.push(allCheckRules(that, 'pGroupItem', (index + 1)))
            arr.push(allCheckRules(that, 'pGroupItemTitle', (index + 1)))
          })

          Promise.all(arr).then(function () { //都通过了
            that.ruleForm.pointsGroup.push(obj)
          }).catch((err) => {
            this.$message({ message: '请填写完整信息', type: 'warning' })
            console.log("err");
          })
        },
        // 添加img的函数
        addImgFc(pGroupIndex) {
          this.pGroupIndex = pGroupIndex
          this.$refs.myInput.value = ''
          this.$refs.myInput.click()
          // this.addImg = true
        },
        addTextFc(pGroupIndex) {
          this.TextTitle = '添加文本'
          this.pGroupIndex = pGroupIndex
          this.addText = true
        },
        //  弹框的img取消
        gloablImgCancel() {
          this.addImg = false
          this.globalImg = []
        },
        // 弹框的img确认
        gloablImgConfirm() {
          let obj = { imgList: {}, type: 'img', IsDel: false }
          if (this.isImgUpdataState) {
            // 修改图片
          } else {
            this.$refs.cropper.getCropBlob((data) => {
              var imgUrl = window.URL.createObjectURL(data)
              // http(config.url + 'cosv5', 'POST', {}).then(pos => {
              //   Bucket = pos.data.Bucket
              //   Region = pos.data.Region
              //   this.uploadImgFn(img, Bucket, Region).then(res => {
              //     obj.imgList.url = 'https://' + res.Location
              //     list.content.push(obj)
              //     console.log(res, 'res')
              //   }).catch(reserr => {
              //     console.log(reserr, 'reserr')
              //   })
              // }).catch(err => {
              //   console.log(err)
              // })
              // 添加到content循环list中去
              obj.imgList.url = imgUrl
              this.ruleForm.pointsGroup[this.pGroupIndex].points.push(obj)
            })
          }
          this.addImg = false
          this.globalImg = []
        },
        // 弹框的text确认
        gloablTextConfirm() {
          let obj = { val: '', type: 'text', IsDel: false }
          this.addText = false
          if (this.isTextUpdataState) {
            this.ruleForm.pointsGroup[this.pointsNum].points[this.pointsItemIndex].val = this.globalText
          } else {
            if (this.globalText !== '') {
              obj.val = this.globalText
              this.ruleForm.pointsGroup[this.pGroupIndex].points.push(obj)
            }
          }
          this.isTextUpdataState = false
          this.globalText = ''
        },
        // 弹框的text取消
        gloablTextCancel() {
          this.addText = false
          this.globalText = ''
        },
        // 总提交
        submitForm() {
          let that = this
          let arr = []
          console.log(this.$refs)
          arr.push(allCheckRules(that, 'ruleForm'))
          // pGroupItem
          let list = this.ruleForm.pointsGroup
          list.map((item, index) => {
            arr.push(allCheckRules(that, 'pGroupItem', (index + 1)))
            arr.push(allCheckRules(that, 'pGroupItemTitle', (index + 1)))
          })
          Promise.all(arr).then(() => {
            alert('yes')
            console.log(this.ruleForm)
          }).catch((err) => {
            this.$message({ message: '请填写完整信息', type: 'warning' })
            console.log('err', err)
          })
        },
        // 删除商品
        delpoints(pGroupIndex, pointsIndex) {
          // this.ruleForm.points.splice(pointsIndex, 1)
          let list = this.ruleForm.pointsGroup[pGroupIndex]
          list.points.splice(pointsIndex, 1)
        },
        // 取消删除商品
        pointsCancel(pGroupIndex, pointsIndex) {
          this.ruleForm.pointsGroup[pGroupIndex].points[pointsIndex].IsDel = false
        },
        uploadImgFn(imgUrl, Bucket, Region) {
          return new Promise((res, rej) => {
            cos.sliceUploadFile({
              Bucket,
              Region,
              Key: 'images/' + new Date().getTime(),
              Body: imgUrl,
              onHashProgress: function (progressData) {
                console.log('校验中', JSON.stringify(progressData));
              },
              onProgress: function (progressData) {
                console.log('上传中', JSON.stringify(progressData));
              },
            },(err, data) => {
              if (err) {
                rej(err)
              } else {
                res(data)
              }
            });
          })
        },
      }
    })
  </script>
</body>

</html>